package applist

import jdk.nashorn.internal.objects.Global
import java.net.URLDecoder
import javax.crypto.Cipher
import javax.crypto.SecretKeyFactory
import redis.clients.jedis.Protocol.CHARSET
import java.io.File
import java.io.FileInputStream
import java.io.InputStreamReader
import java.nio.charset.Charset
import java.nio.file.Files
import java.nio.file.Paths
import java.util.*
import javax.crypto.spec.DESKeySpec




fun urldecode(arg: String): String {
    try {
        return if (arg.indexOf(" ") == -1) {
            URLDecoder.decode(arg, "utf8")
        } else arg
    } catch (e: Exception) {
        return arg
    }

}

@Throws(Exception::class)
fun desDecode(key: String, data: ByteArray): ByteArray {
    try {
        val b = key.toByteArray(Charset.forName("utf8"))
        val dks = DESKeySpec(b)
        val keyFactory = SecretKeyFactory.getInstance("DES")
        //key的长度不能够小于8位字节
        val secretKey = keyFactory.generateSecret(dks)
        val cipher = Cipher.getInstance("DES/ECB/PKCS5Padding")
        //            IvParameterSpec iv = new IvParameterSpec(key.getBytes());
        //            AlgorithmParameterSpec paramSpec = iv;
        cipher.init(Cipher.DECRYPT_MODE, secretKey)
        return cipher.doFinal(data)
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return ByteArray(0)
}

fun decodeLine(line:String):String {
    val splitStrs = line.split(",")
    val key = splitStrs[1]
    val data = Base64.decode(urldecode(splitStrs[2]))
    return String(desDecode(key, data))
}

fun main(args: Array<String>) {
    val sc = Scanner(Thread.currentThread().javaClass.getResourceAsStream("/1"))
    val o = File("2")
    while (sc.hasNext()){
        val line = sc.nextLine()
        o.writeText(decodeLine(line))
    }
    println()
}